package com.wa.handler;
import cn.hutool.core.util.StrUtil;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.corundumstudio.socketio.listener.EventInterceptor;
import com.corundumstudio.socketio.transport.NamespaceClient;
import com.wa.constants.UserTypeConstant;
import com.wa.constants.WebSocketChannelTypeConstant;
import com.wa.enums.NameSpaceEnum;
import com.wa.util.WebSocketSessionKeyUtil;
import com.wa.util.WebSocketSessionManager;
import com.wa.my.util.WebSocketUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;

/**
 * @author recharde.li@allchips.com
 * @version V1.0
 * @date 2020-05-28 16:35
 **/
//@Component
public class WebSocketConnectHandler implements ConnectListener, DisconnectListener, EventInterceptor {

    /**
     * logger
     */
    private Logger logger = LoggerFactory.getLogger(WebSocketConnectHandler.class);

    /**
     * socketIOServer
     */
    private final SocketIOServer socketIOServer;

    /**
     * 关系维护
     */
    private final WebSocketSessionManager webSocketSessionManager;

//    @Resource
//    BaseService baseService;

    @Autowired
    public WebSocketConnectHandler(SocketIOServer socketIOServer, WebSocketSessionManager webSocketSessionManager) {
        this.socketIOServer = socketIOServer;
        this.webSocketSessionManager = webSocketSessionManager;
    }

    @Override
    public void onConnect(SocketIOClient socketIOClient) {
        String key = generateCacheKey(socketIOClient);
        if (StrUtil.isNotEmpty(key)) {
            webSocketSessionManager.saveClient(key, socketIOClient.getSessionId());
        }
    }

    @Override
    public void onDisconnect(SocketIOClient socketIOClient) {
        webSocketSessionManager.deleteSessionClient(socketIOClient.getSessionId());
    }

    @Override
    public void onEvent(NamespaceClient namespaceClient, String s, List<Object> list, AckRequest ackRequest) {

    }

    /**
     * 缓存键生成
     *
     * @param socketIOClient
     * @return
     */
    public String generateCacheKey(SocketIOClient socketIOClient) {
        HandshakeData handshakeData = socketIOClient.getHandshakeData();
        String userType = handshakeData.getSingleUrlParam("b");
        String chanel = handshakeData.getSingleUrlParam("a");
        // 后台用户
        if (Objects.equals(String.valueOf(WebSocketChannelTypeConstant.WEBSITE_CHANNEL), chanel) && Objects.equals(String.valueOf(UserTypeConstant.BACKEND_USER), userType)) {
            String namespace = socketIOClient.getNamespace().getName();
            Object id = getUserId(userType,  WebSocketUtil.getHttpRequestToken(handshakeData.getHttpHeaders().get(WebSocketUtil.COOKIE_HEADER_NAME)));
            if (id != null && Objects.equals(String.valueOf(NameSpaceEnum.BOM.getCodeEn()), namespace)) {
                return WebSocketSessionKeyUtil.buildWebsiteBackendBomKey(String.valueOf(id));
            }
            if (id != null && Objects.equals(String.valueOf(NameSpaceEnum.BOSS.getCodeEn()), namespace)) {
                return WebSocketSessionKeyUtil.buildWebsiteBackendBossKey(String.valueOf(id));
            }
        }
        // 游客   这里处理逻辑有问题
        if (Objects.equals(String.valueOf(WebSocketChannelTypeConstant.WEBSITE_CHANNEL), chanel) && Objects.equals(String.valueOf(UserTypeConstant.VISITOR), userType)) {
            String namespace = socketIOClient.getNamespace().getName();
            Object id = getUserId(userType,  WebSocketUtil.getHttpRequestToken(handshakeData.getHttpHeaders().get(WebSocketUtil.COOKIE_HEADER_NAME)));
            if (id != null && Objects.equals(String.valueOf(NameSpaceEnum.BOM_SAAS.getCodeEn()), namespace)) {
                //return WebSocketSessionKeyUtil.buildWebsiteVisitorKey(String.valueOf(id));
            }
        }
        return null;
    }

    /**
     * @param userType
     * @param token
     * @return
     */
    private Object getUserId(String userType, String token) {
        if(Objects.equals(String.valueOf(UserTypeConstant.BACKEND_USER), userType)) {
//            BackendUserPojo backendUserInfo = baseService.getBackendUserInfoByToken(token);
//            if (null != backendUserInfo && backendUserInfo.getUser() != null) {
//                return backendUserInfo.getUser().getUserId();
//            }
        }
        return null;
    }

}
